//
//  TomAndJerryEpisode.m
//  Travelling Together
//
//  Created by 李宁 on 15/11/30.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "TomAndJerryEpisode.h"

#import <AVOSCloudIM/AVOSCloudIM.h>
@interface TomAndJerryEpisode()<AVIMClientDelegate>
@end
@implementation TomAndJerryEpisode
- (void)tomSendMessageToJerry {
    // Tom 创建了一个 client
    self.client = [[AVIMClient alloc] init];
    
    // Tom 用自己的名字作为 ClientId 打开 client
    [self.client openWithClientId:@"Tom" callback:^(BOOL succeeded, NSError *error) {
        // Tom 建立了与 Jerry 的会话
        [self.client createConversationWithName:@"猫和老鼠" clientIds:@[@"Jerry"] callback:^(AVIMConversation *conversation, NSError *error) {
            // Tom 发了一条消息给 Jerry
            [conversation sendMessage:[AVIMTextMessage messageWithText:@"耗子，起床！" attributes:nil] callback:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    NSLog(@"发送成功！");
                }
            }];
        }];
    }];
}

- (void)jerryReceiveMessageFromTom {
    // Jerry 创建了一个 client
    self.client = [[AVIMClient alloc] init];
    
    // 设置 client 的 delegate，并实现 delegate 方法
    self.client.delegate = self;
    
    // Jerry 用自己的名字作为 ClientId 打开了 client
    [self.client openWithClientId:@"Jerry" callback:^(BOOL succeeded, NSError *error) {
        NSLog(@"Jerry");
        NSLog(@"error=%@",error);
        NSLog(@"%ld",self.client.status);
    }];
}

//查询会话中的消息
- (void)tomQueryMessagesWithLimit {
    // Tom 创建了一个 client
    self.client = [[AVIMClient alloc] init];
    
    // Tom 用自己的名字作为 ClientId 打开 client
    [self.client openWithClientId:@"Tom" callback:^(BOOL succeeded, NSError *error) {
        // Tom 创建查询会话的 query
        AVIMConversationQuery *query = [self.client conversationQuery];
        // Tom 获取 id 为 2f08e882f2a11ef07902eeb510d4223b 的会话
        [query getConversationById:@"565bfacd60b28da5666329bd" callback:^(AVIMConversation *conversation, NSError *error) {
            // 查询对话中最后 10 条消息
            [conversation queryMessagesWithLimit:10 callback:^(NSArray *objects, NSError *error) {
                NSLog(@"查询成功！");
                AVIMTextMessage * a =objects[0];
               
                NSLog(@"有%ld条数据",objects.count);
                NSLog(@"信息=%@",a.text);NSLog(@"location=%@", a.location);
            }];
        }];
    }];
}
#pragma mark - AVIMClientDelegate

// 接收消息的回调函数
- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message {
    NSLog(@"%@", message.text); // 耗子，起床！
    NSLog(@"AVIMClientDelegate");
}
@end
